'use strict'

const titbit = require('titbit')
const { cookie, session } = require('titbit-toolkit')

const app = new titbit({
    debug: true
})

app.use((new cookie()).mid())
//一定要在cookie之后，session是基于cookie的{cookie保存的是session的文件名}
app.use((new session()).mid())

//②第二个
// app.use(async(c,next)=>{
//     //检测有无cookie,发送set-cookie
//     if (c.headers['cookie']===undefined){
//         c.setHeader('set-cookie','key=1234')
//     }
//     await next()
// })

app.use(async,(c,next)=>{
    console.log('just for home')
    await next()
    //添加只针对home分组执行的中间件
},{group:'home'})

app.get('/', async c => {
    c.res.body = 'success'
},{name:'首页',group:'home'})//路由的名字，分组


app.get('/cookie', async c => {
    c.res.body = c.headers['cookie'] || '还没有设置cookie'
})


app.get('/login', async c => {
    c.res.body = `<!DOCTYPE html><html>
        <head>
            <meta charset="utf-8">
        </head>
        <body>
            <form action="/login" method="post">
                <input type="text" name="username">
                <input type="password" name="passwd">
                <input type="submit" name="Login">
            </form>
        </body>
        </html>`
})

app.post('/login',async c=>{
    //提交数据解析到c.body
    // console.log(c.body)
    // c.res.body = c.body
    let {username,passwd}=c.body

    if(username === 'testuser' && passwd === '1234567'){
        c.setSession('is_login',true)
        //登陆成功跳转到首页
        c.status(301)
        c.setHeader('Location','/')
    }else{
        //登陆失败跳转登陆页面
        c.status(301)
        c.setHeader('Location','login')
    }
})



app.run(1256)